package com.yeyv.net.Web.Utils;

import com.yeyv.net.UsefulEntity.Constant;
import com.yeyv.net.UsefulEntity.RedisUtil;
import org.dromara.hutool.extra.mail.MailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class SendMail {
    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private RedisUtil redisUtill;

    String htmlTemplate = """
             
            """;

    public void send(String to, String title, String msg) {
        // 发送邮件
        SimpleMailMessage smm = new SimpleMailMessage();
        smm.setSubject(title);
        smm.setFrom("yeyvop@163.com");
        smm.setTo(to);
        smm.setSentDate(new Date());
        smm.setText(msg);
        javaMailSender.send(smm);

    }

    public String getCodeTemplate(String code, String use) {
        var result = htmlTemplate;
        for (int i = 0; i < code.length(); i++) {
            result = result.replaceFirst("%codeIndex", code.substring(i, i + 1));
        }
        result = result.replace("%useSlot", use).replace("%codeSlot", code);
        return result;
    }

    public void sendVerifyCode(String email) {
        var code = Constant.random(5).toUpperCase();
        redisUtill.set("YV-EMAIL-VERIFYCODE-" + email, code, 3600);
        // 发送html邮件
        MailUtil.sendHtml(email, "若雨验证码" , getCodeTemplate(code, "邮箱验证码"));
    }

    public boolean checkVerifyCode(String email, String code) {
        return code.equals(redisUtill.get("YV-EMAIL-VERIFYCODE-" + email));
    }
}
